<?php

defined('SYSPATH') or die('Access error!');

/**
 * cookie操作类
 */
class Cookie
{

    public static $salt = NULL;
    public static $path = '/';
    public static $domain = NULL;
    public static $secure = FALSE;
    public static $httponly = FALSE;

    /**
     * 判断cookie变量是否存在
     * 
     * @access public
     * @param string $cookie_name	cookie的变量名
     * @return boolean
     */
    public static function is_set($cookie_name)
    {

        if (!$cookie_name)
        {
            return false;
        }

        return isset($_COOKIE[$cookie_name]);
    }

    /**
     * 获取某cookie变量的值
     * 
     * 获取的数值是进过64decode解密的,注:参数支持数组
     * @access public
     * @param string $cookie_name	cookie变量名
     * @return string
     */
    public static function get($cookie_name)
    {
        if (!$cookie_name || !isset($_COOKIE[$cookie_name]))
        {
            return false;
        }

        if (is_array($_COOKIE[$cookie_name]))
        {
            $temp = array();
            foreach ($_COOKIE[$cookie_name] as $key => $value)
            {
                $temp[$key] = unserialize(base64_decode($value));
            }

            return $temp;
        }
        else
        {
            return unserialize(base64_decode($_COOKIE[$cookie_name]));
        }
    }

    /**
     * 设置某cookie变量的值
     * 
     * 注:这里设置的cookie值是经过64code加密过的,要想获取需要解密.参数支持数组
     * @access public
     * @param string $name 	cookie的变量名
     * @param string $value 	cookie值
     * @param intger $expiration	cookie所持续的有效时间,默认为一小时.(这个参数是时间段不是时间点,参数为一小时就是指从现在开始一小时内有效)
     * @param string $path	cookie所存放的目录,默认为网站根目录
     * @param string $domain	cookie所支持的域名,默认为空
     * @return void	
     */
    public static function set($name, $value, $expiration = '')
    {
        //参数分析.
        $expiration = empty($expiration) ? Date::get_time() + 60 * 60 * 24 * 7 : $expiration;
        //数据加密处理.	
        $value = base64_encode(serialize($value));
        setcookie($name, $value, $expiration, Cookie::$path, Cookie::$domain, Cookie::$secure, Cookie::$httponly);
    }

    /**
     * 删除某个Cookie值
     * 
     * @access public
     * @param string $name	cookie的变量值
     * @return void
     */
    public static function delete($name)
    {
        if (!isset($_COOKIE[$name]))
        {
            return TRUE;
        }
        if (is_array($_COOKIE[$name]))
        {
            foreach ($_COOKIE[$name] as $key => $value)
            {
                Cookie::set($name.'['.$key.']', '', '-3600');
                unset($_COOKIE[$name][$key]);
            }
        }
        else
        {
            Cookie::set($name, '', '-3600');
            unset($_COOKIE[$name]);
        }
    }

    /**
     * 清空cookie
     * 
     * @access public
     * @return void
     */
    public static function clear()
    {
        unset($_COOKIE);
    }

}